const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const path = require('path');
const sequelize = require('./config/database');
const deviceRoutes = require('./routes/devices');
const printJobRoutes = require('./routes/printJobs');
const printerRoutes = require('./routes/printer');
const fileRoutes = require('./routes/files');
const initializeData = require('./config/initData');
const { Task, File, Printer } = require('./models');

// 导入所有模型及其关联关系
require('./models');

const app = express();
const PORT = process.env.PORT || 9001;

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 路由
app.use('/api/devices', deviceRoutes);
app.use('/api/print-jobs', printJobRoutes);
app.use('/api/printers', printerRoutes);
app.use('/api/files', fileRoutes);

// 静态文件服务
app.use('/uploads', express.static('uploads'));

// 健康检查
app.get('/health', (req, res) => {
    res.json({ status: 'ok' });
});

// 同步数据库模型到数据库表
(async () => {
  try {
    console.log('开始同步数据库模型...');
    
    // 检查数据库文件是否存在
    const dbPath = path.join(__dirname, '../database_new.sqlite');
    const isNewDatabase = !require('fs').existsSync(dbPath);
    
    // 如果是新数据库，使用 force: true 创建所有表
    // 如果是已存在的数据库，使用 force: false 保留数据
    await sequelize.sync({ force: isNewDatabase });
    
    console.log('数据库模型同步完成');
    
    // 初始化数据
    await initializeData();
    
    // 启动服务器，监听所有网卡接口，而不仅仅是localhost
    app.listen(PORT, '0.0.0.0', () => {
      console.log(`服务器运行在 http://0.0.0.0:${PORT}`);
      
      // 获取并显示本机IP地址，便于局域网访问
      const os = require('os');
      const networkInterfaces = os.networkInterfaces();
      console.log('可通过以下地址访问：');
      
      // 遍历所有网络接口
      Object.keys(networkInterfaces).forEach((interfaceName) => {
        const interfaces = networkInterfaces[interfaceName];
        // 过滤出IPv4地址且非内部地址
        const externalInterfaces = interfaces.filter((iface) => {
          return iface.family === 'IPv4' && !iface.internal;
        });
        
        externalInterfaces.forEach((iface) => {
          console.log(`http://${iface.address}:${PORT}`);
        });
      });
    });
  } catch (error) {
    console.error('数据库同步失败:', error);
  }
})(); 